package com.hongmeng.operater.service.operaterUser.impl;

import com.hongmeng.common.constant.Constants;
import com.hongmeng.common.constant.UserConstants;
import com.hongmeng.common.core.domain.AjaxResult;
import com.hongmeng.common.core.domain.entity.SysRole;
import com.hongmeng.common.core.domain.entity.SysUser;
import com.hongmeng.common.exception.BaseException;
import com.hongmeng.common.utils.DateUtils;
import com.hongmeng.common.utils.SecurityUtils;
import com.hongmeng.operater.domain.operaterUser.HmDoctorAgent;
import com.hongmeng.operater.mapper.operaterUser.HmDoctorAgentMapper;
import com.hongmeng.operater.service.operaterUser.IHmDoctorAgentService;
import com.hongmeng.system.mapper.SysRoleMapper;
import com.hongmeng.system.service.impl.SysUserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 医生经纪人信息Service业务层处理
 *
 * @author hongmeng
 * @date 2021-02-22
 */
@Slf4j
@Service
public class HmDoctorAgentServiceImpl implements IHmDoctorAgentService
{
    @Autowired
    private HmDoctorAgentMapper hmDoctorAgentMapper;

    @Autowired
    private SysUserServiceImpl userService;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    /**
     * 查询医生经纪人信息
     *
     * @param id 医生经纪人信息ID
     * @return 医生经纪人信息
     */
    @Override
    public HmDoctorAgent selectHmDoctorAgentById(Integer id)
    {
        return hmDoctorAgentMapper.selectHmDoctorAgentById(id);
    }

    /**
     * 查询医生经纪人信息列表
     *
     * @param hmDoctorAgent 医生经纪人信息
     * @return 医生经纪人信息
     */
    @Override
    public List<HmDoctorAgent> selectHmDoctorAgentList(HmDoctorAgent hmDoctorAgent)
    {
        return hmDoctorAgentMapper.selectHmDoctorAgentList(hmDoctorAgent);
    }

    /**
     * 新增医生经纪人信息
     *
     * @param hmDoctorAgent 医生经纪人信息
     * @return 结果
     */
    @Transactional
    @Override
    public AjaxResult insertHmDoctorAgent(HmDoctorAgent hmDoctorAgent)
    {
        String createBy="";
        Date nowTime = DateUtils.getNowDate();
        if (SecurityUtils.isLogin()){
            createBy = SecurityUtils.getUsername();
        }
        //新增医生经纪人的用户信息
        SysUser user = new SysUser();
        user.setNickName(hmDoctorAgent.getAgentName());
        user.setUserName(hmDoctorAgent.getPhone());
        user.setSex(hmDoctorAgent.getSex());
        user.setPassword(SecurityUtils.encryptPassword(Constants.DEFAULT_PASS_WORD));
        user.setPhonenumber(hmDoctorAgent.getPhone());
        user.setEmail(hmDoctorAgent.getEmail());
        user.setStatus(Constants.USER_STATE.NORMAL);//初始状态正常
        //用户类型为医生经纪人
        user.setUserType(Constants.USER_TYPE.DOCTOR_AGENT);
        user.setCreateBy(createBy);
        user.setCreateTime(nowTime);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            log.error("新增医生经纪人'" + user.getUserName() + "'失败，手机号码已存在");
            throw new BaseException("新增医生经纪人'" + user.getUserName() + "'失败，手机号码已存在");
        }
        userService.insertUser(user);
        //用户角色为企业
        SysRole selectRole = new SysRole();
        selectRole.setRoleKey(Constants.ROLE_KEY.DOCTOR_AGENT);
        List<SysRole> selectRoleList = sysRoleMapper.selectRoleList(selectRole);
        if (selectRoleList.size()!=1){
            log.error("不存在医生经纪人角色");
            throw new BaseException("新增医生经纪人出现问题，请联系管理员");
        }
        Long[] roleIds = {selectRoleList.get(0).getRoleId()};
        user.setRoleIds(roleIds);
        userService.insertUserRole(user);
        //新增医生经纪人信息
        hmDoctorAgent.setCreateBy(createBy);
        hmDoctorAgent.setCreateTime(nowTime);
        hmDoctorAgent.setUserId(user.getUserId());
        int count = hmDoctorAgentMapper.insertHmDoctorAgent(hmDoctorAgent);
        log.info("新增医生经纪人信息共{}条",count);
        return AjaxResult.success(hmDoctorAgent);
    }

    /**
     * 修改医生经纪人信息
     *
     * @param updateDoctorAgent 医生经纪人信息
     * @return 结果
     */
    @Transactional
    @Override
    public AjaxResult updateHmDoctorAgent(HmDoctorAgent updateDoctorAgent)
    {
        log.info("修改医生经纪人信息，id："+updateDoctorAgent.getId());
        String updateBy="";
        Date nowTime = DateUtils.getNowDate();
        if (SecurityUtils.isLogin()){
            updateBy = SecurityUtils.getUsername();
        }
        HmDoctorAgent doctorAgent = hmDoctorAgentMapper.selectHmDoctorAgentById(updateDoctorAgent.getId());
        if (doctorAgent==null){
            log.error("无法获取id为:{}的医生经纪人信息",updateDoctorAgent.getId());
            throw new BaseException("无法获取id为："+updateDoctorAgent.getId()+"的医生经纪人信息");
        }
        SysUser user = userService.selectUserById(doctorAgent.getUserId());
        if (user == null){
            log.error("当前医生经纪人数据存在问题，请反馈给管理员");
            throw new BaseException("当前医生经纪人数据存在问题，请反馈给管理员");
        }
        //修改企业用户信息
        user.setNickName(updateDoctorAgent.getAgentName());
        user.setPhonenumber(updateDoctorAgent.getPhone());
        user.setEmail(updateDoctorAgent.getEmail());
        user.setSex(updateDoctorAgent.getSex());
        user.setUpdateBy(updateBy);
        user.setUpdateTime(nowTime);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            throw new BaseException("修改医生经纪人'" + user.getUserName() + "'失败，手机号码已存在");
        }
        userService.updateUser(user);
        //修改企业信息
        doctorAgent.setUpdateBy(updateBy);
        doctorAgent.setUpdateTime(nowTime);
        int count = hmDoctorAgentMapper.updateHmDoctorAgent(doctorAgent);
        log.info("更新医生经纪人信息共{}条,医生经纪人id:{},用户id{}",count,doctorAgent.getId(),user.getUserId());
        return AjaxResult.success(doctorAgent);
    }

    /**
     * 批量删除医生经纪人信息
     *
     * @param ids 需要删除的医生经纪人信息ID
     * @return 结果
     */
    @Override
    public int deleteHmDoctorAgentByIds(Integer[] ids)
    {
        int count=0;
        //删除医生经纪人的用户信息
        for (Integer doctorAgentId :ids) {
            count+=deleteHmDoctorAgentById(doctorAgentId);
        }
        log.info("删除医生经纪人信息共{}条",count);
        return count;
    }

    /**
     * 删除医生经纪人信息
     *
     * @param id 医生经纪人信息ID
     * @return 结果
     */
    @Override
    public int deleteHmDoctorAgentById(Integer id)
    {
        HmDoctorAgent doctorAgent = hmDoctorAgentMapper.selectHmDoctorAgentById(id);
        if (doctorAgent==null){
            log.error("没有id为"+id+"的企业信息。");
            throw new BaseException("没有id为"+id+"的企业信息");
        }
        userService.checkUserAllowed(new SysUser(doctorAgent.getUserId()));
        userService.deleteUserById(doctorAgent.getUserId());
        //删除医生经纪人信息信息
        return hmDoctorAgentMapper.deleteHmDoctorAgentById(id);
    }
}